//
//  Extension+UIControl.swift
//  ProductBase
//
//  Created by apple on 2020/7/22.
//  Copyright © 2020 东信北邮信息技术有限公司. All rights reserved.
//

import UIKit
struct RuntimeKey {
    static let topKey = UnsafeRawPointer.init(bitPattern: "topKey".hashValue)
    static let leftKey = UnsafeRawPointer.init(bitPattern: "leftKey".hashValue)
    static let bottomKey = UnsafeRawPointer.init(bitPattern: "bottomKey".hashValue)
    static let rightKey = UnsafeRawPointer.init(bitPattern: "rightKey".hashValue)
}

extension UIControl {
    
    func setEnlargeEdge(_ edge: CGFloat){
        
        objc_setAssociatedObject(self, RuntimeKey.topKey!, edge, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        
        objc_setAssociatedObject(self, RuntimeKey.leftKey!, edge, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        
        objc_setAssociatedObject(self, RuntimeKey.bottomKey!, edge, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        
        objc_setAssociatedObject(self, RuntimeKey.rightKey!, edge, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        
    }
    
    func setEnlarge(top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat){
        
        objc_setAssociatedObject(self, RuntimeKey.topKey!, top, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        
        objc_setAssociatedObject(self, RuntimeKey.leftKey!, left, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
        
        objc_setAssociatedObject(self, RuntimeKey.bottomKey!, bottom, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY);
        
        objc_setAssociatedObject(self, RuntimeKey.rightKey!, right, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY);
        
    }
    
    
    func enlargeRect() -> CGRect{
        
        let top = objc_getAssociatedObject(self, RuntimeKey.topKey!);
        let left = objc_getAssociatedObject(self, RuntimeKey.leftKey!);
        let bottom = objc_getAssociatedObject(self, RuntimeKey.bottomKey!);
        let right = objc_getAssociatedObject(self, RuntimeKey.rightKey!);
        
        if top == nil || left == nil || bottom == nil || right == nil {
            return self.bounds;
        }
        
        
        let top1 = top as! CGFloat
        let left1 = left as! CGFloat
        let bottom1 = top as! CGFloat
        let right1 = right as! CGFloat

        return CGRect(x: self.bounds.origin.x - left1, y: self.bounds.origin.y - top1, width: self.bounds.size.width + left1 + right1, height: self.bounds.size.height + top1 + bottom1)
        
    }
    
    open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        
        let rect  = enlargeRect()
        
        if rect.equalTo(self.bounds){
            return super.hitTest(point, with: event)
        }
        
        return rect.contains(point) ? self : nil
        
    }
    
}
